package utstat.listeners;

import java.util.HashMap;
import java.util.Map;

import utstat.UtEvent;
import utstat.UtEventListener;
import static utstat.Type.*;
import static utstat.Weapon.*;

/**
 * 3 knife kills in a game
 */
public class RevengeListener implements UtEventListener {


	private Map<String, Integer> dominations = new HashMap<String, Integer>();
	private Map<String,LastKill> lastKills = new HashMap<String, LastKill>();
	
	private int currentRound = -1;

	@Override
	public String getIntestingFact(String player) {
		return null;
	}

	@Override
	public void processEvent(UtEvent e) {

		if (e.getRound() != currentRound) {
			nextRound();
			currentRound = e.getRound();
		}

		if (e.getType() != kill || e.getSrc() == null || e.getSrc().equals(e.getDest())) return;

		String domKey = e.getSrc() + e.getDest();
		String revKey = e.getDest() + e.getSrc();

		increment(domKey, dominations);

		if (dominations.get(domKey) == 3) {
	//		System.out.println(e.getSrc() + " is dominating " + e.getDest()+"!");

		}

		if (dominations.get(revKey) != null && dominations.get(revKey) > 2) {
	//		System.out.println(e.getSrc() + " got revenge on " + e.getDest() + " after " + dominations.get(revKey) + " kills!");

		}
		dominations.put(revKey, 0);
		
		LastKill thisKill = new LastKill(e.getDest());
		LastKill destKill = lastKills.get(e.getDest());
		thisKill.lastKilled = destKill;
		lastKills.put(e.getSrc(), thisKill);

		if(dominations.get(domKey)>1) { /*already avenged*/ return; }
		
		
		if(getDepthsOfRevenge(thisKill,e.getSrc())>3&&e.getPlayerTeams().size()>4) {
			System.out.println(getDepthsOfRevenge(thisKill,e.getSrc())+": "+getRevengePath(thisKill,e.getSrc()));}
		
	}

	private int getDepthsOfRevenge(LastKill k,String src) {
		if(k==null) return 0;
		if(k.lastKilled==null||!k.lastKilled.name.equals(src)) return 1;
		return 1+getDepthsOfRevenge(k.lastKilled,k.name);
	}
	
	private String getRevengePath(LastKill k,String src) {
		if(k==null) return "";
		if(k.lastKilled==null||!k.lastKilled.name.equals(src)) return src;
		return src+" -> "+getRevengePath(k.lastKilled,k.name);
	}

	private int increment(String player, Map<String, Integer> countMap) {
		Integer count = countMap.get(player);
		if (count == null) count = 0;
		count++;
		countMap.put(player, count);
		return count;
	}

	private void nextRound() {
		System.out.println("-----");
		dominations = new HashMap<String, Integer>();
		lastKills = new HashMap<String, LastKill>();
	}
	
	private class LastKill {
		LastKill lastKilled;
		String name;
		LastKill(String name) {this.name=name;}
	}

}
